<!--
 * @Author: Nico
-->
<template>
  <div class="ui-form pda-form">
    <!--
       :class="[
      'mt-' + (info.extension.topMargin && info.extension.topMargin.value),
      'mr-' + (info.extension.rightMargin && info.extension.rightMargin.value),
      'mb-' + (info.extension.bottomMargin && info.extension.bottomMargin.value),
      'ml-' + (info.extension.leftMargin && info.extension.leftMargin.value),
    ]"
    -->
    <!-- 原代码备份 -->
    <!-- <van-form
      :id="'uiform_' + info._id"
      :ref="info._id"
      v-ui-ref="vSetRef"
      class="h-full"
      :inline="true"
      :label-position="info.extension.labelPosition.value"
      :model="selfFormData"
      :rules="setRules"
      :show-message="true"
      status-icon
      style="flex: 1"
    > -->
    <van-form
      :id="'uiform_' + info._id"
      :ref="info._id"
      v-ui-ref="vSetRef"
      class="h-full"
      :inline="true"
      :model="selfFormData"
      :rules="setRules"
      :show-message="true"
      status-icon
      style="flex: 1"
    >
      <pdaWidget :class="['grid']" :list="info.list" />
      <!-- 原代码备份 -->
      <!-- <pdaWidget :class="['grid cols-' + info.extension.layout.value]" :list="info.list" /> -->
    </van-form>
    <!-- <div>预览formData:{{ selfFormData }}</div> -->
  </div>
</template>
<script>
  import { Form } from 'vant'
  import { defineComponent, defineAsyncComponent } from 'vue'
  import { UiMixin, RefsInjectMixin } from '@ve/mixin'
  import cloneDeep from 'lodash/cloneDeep'
  import isEmpty from 'lodash/isEmpty'
  import trim from 'lodash/trim'
  import isArray from 'lodash/isArray'
  import { getModelInfo } from '@ve/utils/getModelInfo'
  import { getComponentDefaulType, processingConstant, getDefaultDate } from '@ve/utils/utils'
  // import { domHeight, getBody } from '@ve/utils/domHeight'
  export default defineComponent({
    name: 'UiPdaForm',
    components: {
      // 使用异步组件
      pdaWidget: defineAsyncComponent(() => import('@ve/components/pdaWidget.vue')),
      [Form.name]: Form,
    },
    mixins: [UiMixin, RefsInjectMixin],
    provide() {
      return {
        formId: this.info._id,
      }
    },
    props: {
      info: {
        required: true,
        type: Object,
        default: function () {
          return {}
        },
      },
    },
    data() {
      return {
        uiFormBoxHeight: null,
        layerPageHeight: 500,
        lastNewval: {},
        getHasShowScroll1: false,
        // formDataC: {},
      }
    },

    computed: {
      // selfFormData: {
      //   get(newValue) {
      //     if (Object.values(newValue.info.data.formData).length > 1) {
      //       console.log('----222', Object.values(newValue.info.data.formData)[0])
      //       return Object.values(newValue.info.data.formData)[0]
      //     } else {
      //       return this.info.data.formData
      //     }
      //   },
      // },
      selfFormData() {
        return this.info.data.formData
      },
      getHasShowScroll() {
        return this.getHasShowScroll1
      },

      setRules() {
        const rules = cloneDeep(this.info.rules) || {}
        for (let key in rules) {
          const arr = rules[key] || []
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].pattern) {
              arr[i].pattern = new RegExp(arr[i].pattern)
            }
          }
        }
        return rules
      },
    },
    // watch: {
    //   selfFormData(newValue) {
    //     this.formDataC = newValue
    //   },
    // },

    // mounted() {
    //   this.getLayerPageHeight()
    // },
    // activated() {
    //   this.getLayerPageHeight()
    // },
    methods: {
      // getLayerPageHeight() {
      //   setTimeout(() => {
      //     // let _body = getBody(this).find(`#uiform_${this.info._id}`)
      //     // let _domHeight = domHeight(this)
      //     // if (_body.length > 0) {
      //     //   if (_domHeight > 0) {
      //     //     this.layerPageHeight = _domHeight
      //     //   }
      //     //   //是否有滚动条
      //     //   if (_body.length > 0) {
      //     //     let uiFormBoxHeight = _body[0].clientHeight
      //     //     this.getHasShowScroll = uiFormBoxHeight >= this.layerPageHeight ? true : false
      //     //   }
      //     // }
      //     console.log('Nico', this.layerPageHeight)
      //   }, 20)
      // },
      dataSourceChange(newval) {
        // 取消timeOut 防止点击打开图层 -》 数据注入 注入值被覆盖
        let _obj = {}
        // 赋默认值
        if (this.getInfo.data.formItems) {
          Object.keys(this.getInfo.data.formItems).forEach((v) => {
            let model_info = getModelInfo(this, v)
            if (isArray(model_info)) return
            if (model_info && model_info.extension.defaultValue) {
              // console.log(`触发寻找默认值~~~~~~~~${model_info._id} --------------------- ${model_info.extension.defaultValue.value}`)
              _obj[model_info.extension.model.value] = processingConstant(this, model_info.extension.defaultValue.value)
            } else {
              //开关按钮单独获取值
              if (model_info.type === 'uiSwitch') {
                let switchValue = null
                if (model_info.extension.defaultState.value) {
                  switchValue = model_info.extension.activeValue.value
                } else {
                  switchValue = model_info.extension.inactiveValue.value
                }
                _obj[model_info.extension.model.value] = processingConstant(this, switchValue)
              } else if (model_info.type === 'uiDate') {
                // 日期时间组件单独获取值
                if (model_info.extension.defaultDate.value) {
                  // 如果设置默认值为 当前
                  if (model_info.extension.selection.value === 'datetime' || model_info.extension.selection.value === 'date') {
                    // 如果当前组件类型为 datetime 或 date
                    if (model_info.extension.defaultDate.value === 'now') {
                      // 设置 默认值为 当前 的默认值
                      _obj[model_info.extension.model.value] = getDefaultDate('now')
                      // 如果为日期类型则去掉值的时分秒
                      if (model_info.extension.selection.value.indexOf('time') == -1) {
                        _obj[model_info.extension.model.value] = _obj[model_info.extension.model.value].split(' ')[0]
                      }
                    }
                  } else if (model_info.extension.selection.value === 'datetimerange' || model_info.extension.selection.value === 'daterange') {
                    // 如果当前组件类型为 时间范围
                    if (model_info.extension.defaultDate.value !== 'now') {
                      _obj[model_info.extension.model.value] = getDefaultDate(model_info.extension.defaultDate.value)
                      const startSuffix = model_info.extension?.startSuffix?.value ? model_info.extension?.startSuffix?.value : '_start'
                      const endSuffix = model_info.extension?.endSuffix?.value ? model_info.extension?.endSuffix?.value : '_end'
                      _obj[`${model_info.extension.model.value}${startSuffix}`] = _obj[model_info.extension.model.value][0] || ''
                      _obj[`${model_info.extension.model.value}${endSuffix}`] = _obj[model_info.extension.model.value][1] || ''
                      // 如果为日期类型则去掉值的时分秒
                      if (model_info.extension.selection.value.indexOf('time') == -1) {
                        _obj[model_info.extension.model.value][0] = _obj[model_info.extension.model.value][0].split(' ')[0]
                        _obj[model_info.extension.model.value][1] = _obj[model_info.extension.model.value][1].split(' ')[0]
                        _obj[`${model_info.extension.model.value}${startSuffix}`] =
                          _obj[`${model_info.extension.model.value}${startSuffix}`].split(' ')[0]
                        _obj[`${model_info.extension.model.value}${endSuffix}`] =
                          _obj[`${model_info.extension.model.value}${endSuffix}`].split(' ')[0]
                      }
                    }
                  }
                }
              } else {
                _obj[model_info.extension.model.value] = getComponentDefaulType(model_info.type)
              }
            }
          })
        } else {
          // 兼容老的 form 组件 ，如果没有存储 formItems 则调用之前的方法
          Object.keys(this.getInfo.data.formData).map((v) => {
            _obj[v] = ''
          })
        }
        let _mergeData = {}

        // 根据 getDataKey 筛选需要的数据
        if (!trim(this.info.dataSourceBind.getDataKey?.value)) {
          // 如果没有 getDataKey 则返回全量数据
          _mergeData = newval
        } else {
          const keyList = this.info.dataSourceBind.getDataKey?.value.split(',')
          isArray(keyList) &&
            keyList.forEach((item) => {
              item = trim(item)
              if (newval[item] !== undefined) {
                // 如果传过来的对象里面没有要取得值 则丢弃
                _mergeData[item] = newval[item]
              }
            })
        }

        if (this.info.dataSourceBind.getArrayIndex && this.info.dataSourceBind.getArrayIndex.value != 'all') {
          if (_mergeData['data']) {
            _mergeData = _mergeData['data'][this.info.dataSourceBind.getArrayIndex.value]
          }
        }

        let _data = isEmpty(_mergeData)
          ? _obj
          : {
              ...this.getInfo.data.formData,
              ..._mergeData,
            }

        this.getInfo.data.formData = _data
        this.getInfo.data._formData = cloneDeep(_data)
      },
      setFormData(data) {
        console.log('data', data)
        this.getInfo.data.formData = Object.assign(this.getInfo.data.formData, data)
      },
    },
  })
</script>
<style scoped>
  .pda-form {
    display: inline-flex;
    flex-direction: column;
    width: 100%;
    /* height: 95%; */
    /* overflow-y: scroll; */
  }
</style>
